from django.db import models
from django.utils import timezone
import os

class Document(models.Model):
    title = models.CharField('标题', max_length=255)
    file = models.FileField('文件', upload_to='documents/%Y/%m/%d/')
    file_type = models.CharField('文件类型', max_length=50)
    file_size = models.IntegerField('文件大小')
    upload_time = models.DateTimeField('上传时间', default=timezone.now)
    upload_ip = models.GenericIPAddressField('上传IP', null=True, blank=True)
    download_count = models.IntegerField('下载次数', default=0)
    is_shared = models.BooleanField('是否共享', default=False)
    
    class Meta:
        verbose_name = '文档'
        verbose_name_plural = verbose_name
        ordering = ['-upload_time']
    
    def __str__(self):
        return self.title
    
    def save(self, *args, **kwargs):
        if not self.title:
            self.title = os.path.splitext(self.file.name)[0]
        if not self.file_type:
            self.file_type = os.path.splitext(self.file.name)[1][1:].upper()
        if not self.file_size and self.file:
            self.file_size = self.file.size
        super().save(*args, **kwargs)
    
    def delete(self, *args, **kwargs):
        # 删除文件
        if self.file:
            if os.path.isfile(self.file.path):
                os.remove(self.file.path)
        super().delete(*args, **kwargs)
    
    @property
    def file_extension(self):
        """获取文件扩展名"""
        return self.file_type.lower() if self.file_type else ''

class Question(models.Model):
    document = models.ForeignKey(Document, on_delete=models.CASCADE, related_name='questions', verbose_name='所属文档')
    content = models.TextField('题目内容')
    answer = models.TextField('参考答案', blank=True, null=True)
    page_number = models.IntegerField('页码', default=1)
    question_type = models.CharField('题目类型', max_length=50, blank=True, null=True)
    created_at = models.DateTimeField('创建时间', default=timezone.now)
    
    class Meta:
        verbose_name = '题目'
        verbose_name_plural = verbose_name
        ordering = ['page_number', 'id']
    
    def __str__(self):
        return f"{self.document.title} - 第{self.page_number}页 - 题目{self.id}"
